#include "modbus.h"
#include "stm32l1xx_hal.h"
#include "logic.h"
#include "usart.h"
uint8_t  reg8[32];
uint16_t Get_Crc16(uint8_t *CmmBuf, uint8_t Len)
{
    uint16_t crc = 0xFFFF;
    unsigned char i;
    unsigned char j;
    j = 0;
    while(j < Len)
    {
        crc ^= CmmBuf[j];
        for(i=0; i < 8; i++)
        {
            if(crc & 0x01)
            {
                crc >>= 1;
                crc ^= 0xA001;
            }
            else
            {
                crc >>= 1;
            }
        }
        j++;
    }
    CmmBuf[j] = crc % 0x100; //????????,??????3
    CmmBuf[j + 1] = crc / 0x100;
    return crc;
}
void Uart1_Send_Data(uint8_t *pData,uint8_t len)
{
    HAL_UART_Transmit(&huart1,pData,len,0xffff);
}
uint8_t sendBuff[20];
uint8_t baseAddr = 0;
void Uart1_Data_Deal()
{
    uint8_t id = u1Buff[0];
    uint8_t fun  = u1Buff[1];
    uint16_t addr = u1Buff[2]<<8|u1Buff[3];
    uint16_t len  = u1Buff[4]<<8|u1Buff[5];
    uint8_t  bLen = u1Buff[6];
    uint16_t cCrc = Get_Crc16(u1Buff,u1Len-2);
    uint16_t rCrc = u1Buff[u1Len-2]|u1Buff[u1Len-1]<<8;
    if(cCrc != rCrc) return;
    if(id != gSrcAddr && id != 0) return;
    sendBuff[0] = id;sendBuff[1] = fun;sendBuff[2] = len*2;
    if(u1Len == 8 && fun == 0x03) //read regs
    {
        if(addr == 1) baseAddr = 1;
        else if(addr == 2) baseAddr = 3;
        else if(addr == 3) baseAddr = 5;
        for(uint16_t i=0;i<len;i++)
        {
            sendBuff[3+i*2] = reg8[baseAddr + i*2+1] ;
            sendBuff[4+i*2] = reg8[baseAddr + i*2]; 
        }
        cCrc = Get_Crc16(sendBuff,3+len*2);
        sendBuff[3+len*2] = cCrc &0xff;
        sendBuff[4+len*2] = cCrc>>8;
        Uart1_Send_Data(sendBuff,5+len*2);
        if(addr == 2 || addr == 3) 
        {
            if(gAdcState == ADC_FINISH_e)
            {
                gAdcState = ADC_WORK_e;
                HAL_ADC_Start_DMA(&hadc,(uint32_t*)adc_value,1000);
                osSemaphoreRelease(semAdcStartHandle);
            }
        }
    }
    else if(fun == 0x10 )//write regs
    {
        if(addr == 3) baseAddr = 5;
        else return;
        sendBuff[0] = id;sendBuff[1] = fun;sendBuff[2] = addr >>8;sendBuff[3] = addr&0xff;
        sendBuff[4] = len>>8;sendBuff[5] = len&0xff;
        for(uint16_t i=0;i<len;i++)
        {
            reg8[baseAddr + i*2] = u1Buff[8+i*2];
            reg8[baseAddr + i*2+1] = u1Buff[7+i*2]; 
        }
        cCrc = Get_Crc16(sendBuff,6);
        sendBuff[6] = cCrc &0xff;
        sendBuff[7] = cCrc >> 8;
        Uart1_Send_Data(sendBuff,8);
        //if(WORK_MODE == 1) 
        
    }

}
